<?php

namespace app\admin\controller\chase;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\chase\User as UserModel;
use app\admin\model\chase\RealOrderService as RealOrderServiceModel;
use app\admin\model\chase\UserCoupon as UserCouponModel;
use app\admin\model\chase\UserVip as UserVipModel;
use app\admin\model\chase\ModelingService as ModelingServiceModel;
use app\admin\model\chase\Design as DesignModel;

/**
 * 到店消费订单管理
 *
 * @icon fa fa-circle-o
 */
class RealOrder extends Backend
{
    
    /**
     * RealOrder模型对象
     * @var \app\admin\model\chase\RealOrder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\chase\RealOrder;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("paymentList", $this->model->getPaymentList());
        $this->view->assign("categories", \app\admin\model\chase\DesignCategory::getCategories());
        $this->view->assign("services", \app\admin\model\chase\ModelingService::all());
        $this->view->assign("designs", \app\admin\model\chase\Design::all());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['user', 'service.design'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['user', 'service.design'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            array_walk($list, function (&$val) {
                $val['createtime'] = date('Y-m-d H:i:s', $val['createtime']);
            });
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 开单
     */
    public function create()
    {
        return $this->fetch();
    }

    /**
     * 挂单或付款
     */
    public function add()
    {
        $param = $this->request->post();

        if ($param) {
            if (!isset($param['user_id']) || !$param['user_id']) {
                $this->error('请选择用户');
            }
            if (isset($param['user_coupon_id']) && $param['user_coupon_id']) {
                $userCoupon = UserCouponModel::where("id", $param['user_coupon_id'])->find();
                if (!$userCoupon) {
                    $this->error('优惠券不存在');
                }
                if ($userCoupon->user_id != $param['user_id']) {
                    $this->error('请使用当前选中用户的优惠券');
                }
                if ($userCoupon->status != 1) {
                    $this->error('当前优惠券已过期或已使用');
                }
            }
            if (!isset($param['services']) || !$param['services'][0]) {
                $this->error('请选择服务');
            }
            $user = UserModel::find($param['user_id']);
            if (!$user) {
                $this->error('用户不存在');
            }

            Db::startTrans();
            try {
                $order = $this->model->create([
                    'order_no' => 'RO'.date('YmdHis').mt_rand(1000, 9999),
                    'user_id' => $param['user_id'] ?? 0,
                    'user_coupon_id' => $param['user_coupon_id'] ?? 0,
                    'phone' => $user->phone,
                    'username' => $user->nickname,
                    'total_amount' => $param['total_amount'],
                    'real_amount' => $param['real_amount'],
                    'discount_amount' => $param['discount_amount'],
                    'vip_amount' => $param['vip_amount']
                ]);
                RealOrderServiceModel::add($order->id, $param['services']);

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
            }
            isset($e) ? $this->error('挂单失败，请联系管理员') : $this->success('挂单成功', '', ['id'=>$order->id]);

        }
        $this->error('请填写开单信息');
    }

    /**
     * 选择用户
     */
    public function users()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $userModel = new UserModel();
            $total = $userModel->with('userVip')
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $userModel->with('userVip')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            array_walk($list, function (&$val) {
                //会员优惠的折扣
                $val['discount'] = $val['user_vip'] ? (100 - $val['user_vip']['discount']) / 100 : 0;
            });
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加用户
     */
    public function adduser()
    {
        $userVips = UserVipModel::getVips();
        if ($this->request->isPost()) {
            $param = $this->request->post();
            if ($param) {
                $user = UserModel::getByPhone($param['phone']);
                if ($user) {
                    $this->error('该手机号已绑定用户');
                }
                $userModel = new UserModel();
                $result = $userModel->allowField(true)->save($param);
                $result ? $this->success() : $this->error('添加失败，请联系管理员');
            } else {
                $this->error('请填写用户信息');
            }

        }
        $this->assign('userVips', $userVips);
        return $this->fetch();
    }

    /**
     * 选择服务
     */
    public function services()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $serviceModel = new ModelingServiceModel();
            $total = $serviceModel->where($where)
                ->order($sort, $order)
                ->count();

            $list = $serviceModel->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 选择造型师
     */
    public function designs()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $designModel = new DesignModel();
            $total = $designModel->where($where)
                ->order($sort, $order)
                ->count();

            $list = $designModel->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 选择优惠券
     */
    public function coupons($user_id)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $userCouponModel = new UserCouponModel();
            $total = $userCouponModel->where('user_id', $user_id)
                ->where('status', 1)
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $userCouponModel->where('user_id', $user_id)
                ->where('status', 1)
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            array_walk($list, function (&$val) {
                $val['start_time'] = date('Y-m-d H:i:s', $val['start_time']);
                $val['end_time'] = date('Y-m-d H:i:s', $val['end_time']);
            });
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 取消订单
     */
    public function cancel()
    {
        $order_id = $this->request->post('order_id');
        $order = $this->model->find($order_id);
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order->status != 1) {
            $this->error('订单已取消或已完成');
        }
        $order->status = 0;
        $result = $order->save();
        $result ? $this->success() : $this->error('取消失败');
    }

    /**
     * 订单付款
     */
    public function payment($ids, UserVipModel $userVipModel)
    {
        $row = $this->model->with(['user', 'userCoupon', 'service' => function ($query) {
            $query->with(['category', 'design']);
        }])->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        //小程序码
        $row['code'] = \app\admin\model\chase\RealOrder::createCode($ids);
        $row['vip_discount'] = 0;
        if ($row->user) {
            $vip = $userVipModel->getByName($row->user->vip);
            if ($vip) {
                $row['vip_discount'] = (100 - $vip->discount) / 100;
            }
        }


        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();

            if ($params) {
                if (!isset($params['payment'])) {
                    $this->error('请选择付款方式');
                }
                if ($params['real_amount'] <= 0) {
                    $this->error('实际收款必须大于0');
                }

                //余额支付
                if ($params['payment'] == 2) {
                    if (!$row->user) {
                        $this->error('该用户不存在，请使用现金支付或扫码支付');
                    }
                    if ($row->user->money < $params['real_amount']) {
                        $this->error('用户余额不足，请使用现金支付或扫码支付');
                    }
                }
                if ($params['payment'] != 3) {
                    $params['status'] = 2;
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    //使用优惠券
                    if (isset($params['user_coupon_id']) && $params['user_coupon_id']) {
                        UserCouponModel::where('id', $params['user_coupon_id'])->update(['status' => 2]);
                    }
                    RealOrderServiceModel::del($ids);
                    RealOrderServiceModel::add($ids, $params['service']);
                    if ($params['payment'] ) {
                        $row->user->money -= $params['real_amount'];
                        $row->user->expense_money += $params['real_amount'];
                        $row->user->save();
                    }
                    if ($params['payment'] == 1) {
                        $row->user->expense_money += $params['real_amount'];
                        $row->user->save();
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 确认付款
     */
    public function confirm($ids)
    {
        $row = $this->model->with(['user' => function($query) {
            $query->with(['userVip']);
        },'service' => function ($query) {
            $query->with(['category', 'design']);
        }, 'userCoupon'])->find($ids);

        $row['createtime'] = $row['createtime'] ? date('Y-m-d H:i:s', $row['createtime']) : '';
        $row['code'] = \app\admin\model\chase\RealOrder::createCode($ids);

        if ($this->request->isPost()) {

            $payment = $this->request->post('payment');
            if (!$payment) {
                $this->error('请选择付款方式');
            }
            if ($row->status != 1 && $payment != 3) {
                $this->error('订单已取消或已付款');
            }
            $user = UserModel::find($row->user_id);
            if (!$user) {
                $this->error('用户不存在');
            }
            if ($payment == 2 && $user->money < $row->real_amount) {
                $this->error('用户余额不足，请选择其他付款方式');
            }
            Db::startTrans();
            try {
                switch ($payment) {
                    case 1:
                        $user->setInc('expense_money', $row->real_amount);
                        $row->status = 2;
                        break;
                    case 2:
                        $user->setDec('money', $row->real_amount);
                        $user->setInc('expense_money', $row->real_amount);
                        $row->status = 2;
                        break;
                }
                $row->payment = $payment;
                unset($row->code);
                unset($row->createtime);
                $result = $row->save();
                //使用优惠券
                if (isset($params['user_coupon_id']) && $params['user_coupon_id']) {
                    UserCouponModel::where('id', $params['user_coupon_id'])->update(['status' => 2]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
            }
            isset($e) ?  $this->error($e->getMessage()) : $this->success();

        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

        /**
     * 订单详情
     */
    public function detail($ids)
    {
        $row = $this->model->with(['user' => function($query) {
            $query->with(['userVip']);
        },'service' => function ($query) {
            $query->with(['category', 'design']);
        }, 'userCoupon'])->find($ids);

        $row['createtime'] = $row['createtime'] ? date('Y-m-d H:i:s', $row['createtime']) : '';

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
